package com.fitbet.wechat.web.controller.trading;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.wechat.entity.cfg.JsConfig;
import com.fitbet.entity.trading.SalesOrder;
import com.fitbet.entity.user.User;
import com.fitbet.wechat.processor.WechatProcessor;
import com.fitbet.wechat.service.SalesOrderService;
import com.fitbet.wechat.web.interceptor.UserContext;
import com.fitbet.wechat.web.interceptor.UserContextType;
import com.fitbet.wechat.web.resolver.Secure;

/**
 * 
 * @author mohanlan
 *
 */
@RestController
@RequestMapping("/shopping")
public class ShoppingRestController {
    
    private static final Logger logger = LoggerFactory.getLogger(ShoppingRestController.class);
    
    @Autowired
    private SalesOrderService   salesOrderService;
    
    @Autowired
    private WechatProcessor        wechatProcessor;
    
    /**
     * 
     * @param user
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/pay", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @UserContext(type = UserContextType.WECHAT_AUTHORITY)
    public HttpResult prepare(@Secure User user,
                              @RequestParam("order") Long orderId,
                              @RequestParam("currentUrl") String currentUrl,
                              HttpServletRequest request) {
        
        HttpResult httpResult = new HttpResult();
        
        JsConfig jsConfig = wechatProcessor.generateJsConfig(currentUrl);
        
        SalesOrder salesOrder = salesOrderService.load(SalesOrder.class, orderId);
        
        // 1. create order & payment request
        String xRealIpHeader = request.getHeader("X-Real-IP");  // Only available after NGINX redirect
        String remoteIp = StringUtils.isBlank(xRealIpHeader) ? request.getRemoteAddr() : xRealIpHeader;
        logger.trace("#join() - Get remote IP address [{}].", remoteIp);
        
        Map<String, Object> payConfig = salesOrderService.prepay(salesOrder, user, remoteIp);
        
        return httpResult.success()
                .data("payConfig", payConfig)
                .data("jsConfig", jsConfig);
    }
    
}
